import Service from '@/utils/service.js'

export const useRoutesStore = defineStore({
  id: 'routes',
  state: () => ({
    routes: [],
    treeRoutes: [],
    selectedKeys: [],
    openKeys: [],
  }),
  actions: {
    async setRoutes() {
      const list = []
      const { data } = await Service.axiosInstance({
        url: '/routes.json',
        unnecessaryBaseURL: true,
      })
      const routes = data.slice()
      while (routes.length) {
        const item = routes.shift()
        if (item.children) {
          routes.push(...item.children)
        }
        if (item.component !== 'Layout') {
          list.push(item)
        }
      }
      this.routes = list
      this.treeRoutes = data
      const errRoute = {
        path: '/:pathMatch(.*)*',
        redirect: '/404',
      }
      return [...data, errRoute]
    },
    updateMenu({ path, matched }) {
      this.selectedKeys = [matched[0].children.length > 1 ? path : matched[0].path]
      this.openKeys = [matched[0].path]
    },
    resetRoutes() {
      this.routes = []
      this.treeRoutes = []
      this.selectedKeys = []
      this.openKeys = []
    },
  },
})
